package com.xinbochuang.machine.framework.security.custom;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 身份证号认证配置
 *
 * @author 黄晓鹏
 * @date 2020-09-14 11:17
 */
@Component
public class IdCardAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private SuccessAuthenticationHandler successAuthenticationHandler;

    @Resource
    private FailAuthenticationHandler failAuthenticationHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        IdCardAuthenticationFilter idCardAuthenticationFilter = new IdCardAuthenticationFilter();
        idCardAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        idCardAuthenticationFilter.setAuthenticationSuccessHandler(successAuthenticationHandler);
        idCardAuthenticationFilter.setAuthenticationFailureHandler(failAuthenticationHandler);

        IdCardAuthenticationProvider idCardAuthenticationProvider = new IdCardAuthenticationProvider();
        idCardAuthenticationProvider.setUserDetailsService(userDetailsService);

        http.authenticationProvider(idCardAuthenticationProvider)
                .addFilterAfter(idCardAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

}
